<template>
  <div>
    <el-dialog title="提示" v-model="dialogVisible" width="30%">
      <span>确认要删除该条数据吗?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDelete">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 使用批量删除组件 -->
    <BatchDelete
      v-model:visible="batchDeleteDialogVisible"
      :selected-items="selectedRows"
      delete-url="/product/delete"
      id-field="id"
      @delete-success="handleBatchDeleteSuccess"
    />

    <el-container class="product-container">
      <!-- 左侧分类树 -->
      <el-aside width="280px" class="catalog-aside">
        <div class="tree-header">
          <span class="tree-title">商品分类</span>
          <div>
            <el-button type="primary" size="small" @click="refreshCatalogTree">刷新</el-button>
            <el-button type="warning" size="small" @click="clearCatalogFilter">清除</el-button>
          </div>
        </div>
        <el-input
          v-model="treeFilterText"
          placeholder="输入关键字进行过滤"
          clearable
          class="filter-input"
        />
        <div class="tree-container">
          <el-tree
            ref="catalogTree"
            :data="catalogTreeData"
            :props="catalogTreeProps"
            :filter-node-method="filterCatalogNode"
            highlight-current
            node-key="id"
            @node-click="handleCatalogNodeClick"
            class="catalog-tree"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="node-count" v-if="data.count !== undefined">({{ data.count }})</span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-aside>

      <!-- 右侧内容 -->
      <el-main class="product-main">
        <div class="search">
          <el-form label-width="80px">
            <el-row>
              <el-col :span="6" style="padding: 0 8px;">
                <el-form-item label="商品名称">
                  <el-input v-model="searchObject.name" placeholder="商品名称" name="name">
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="18" style="padding: 0 10px;">
                <el-row type="flex" justify="end">
                  <el-button type="primary" @click="search">搜索</el-button>
                  <el-button type="warning" @click="clearCatalogFilter">清除分类</el-button>
                  <el-button plain @click="clearAllSearch">清除全部</el-button>
                </el-row>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="data-content">
          <div class="tool-add">
            <el-button type="primary" @click="addView">新增</el-button>
            <el-button type="success" @click="showImportDialog">Excel导入</el-button>
            <el-button type="danger" @click="showBatchDeleteDialog" :disabled="selectedRows.length === 0">
              批量删除 <span v-if="selectedRows.length > 0">({{ selectedRows.length }})</span>
            </el-button>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData.data"
            @sort-change="changeTableSort"
            style="width: 100%;font-size: 12px;"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="商品编码" prop="id" width="100">
            </el-table-column>
            <el-table-column label="商品名称" prop="name" width="200">
            </el-table-column>
            <el-table-column label="商品分类" prop="catalogName" width="100">
            </el-table-column>
            <el-table-column label="库存" prop="stockNum"
                            sortable="custom" width="100">
            </el-table-column>
            <el-table-column label="上架状态" prop="stateName" width="100">
            </el-table-column>
            <el-table-column label="价格" prop="price"
                            sortable="custom" width="100">
            </el-table-column>
            <el-table-column label="折扣" prop="discount">
            </el-table-column>
            <el-table-column width="280" align="center" fixed="right" label="操作">
              <template #default="scope">
                <el-switch v-model="scope.row.state" :active-value="1" :inactive-value="2"
                          active-text="已上线"
                          inactive-text="已下线"
                          inline-prompt
                          @change="updateProductState(scope.row)"/>
                <el-button text class="operation_bt" :icon="InfoFilled" type="info" @click="showView(scope.row)">详情
                </el-button>

                <el-button text class="operation_bt" :icon="Edit" type="primary" @click="editView(scope.row)">编辑
                </el-button>

                <el-button text :icon="Delete" class="operation_bt" type="danger" style="cursor: pointer;"
                          @click="deleteData(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="page">
            <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 50, 100]"
                          :page-size="pageData.size" :pager-count="5"
                          layout="total, sizes, prev, pager, next, jumper" :page-count="pageData.totalPage"
                          :total="pageData.total" @size-change="sizeChange" @current-change="pageChange">
            </el-pagination>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 使用导入组件 -->
    <ProductImport
      v-model:visible="importDialogVisible"
      :api-url="'/product/create'"
      @import-success="handleImportSuccess"
    />

    <!-- 使用商品详情抽屉组件 -->
    <ProductDetail
      v-model:visible="detailDrawerVisible"
      :product-id="currentProductId"
      @edit="handleEditFromDetail"
    />
  </div>
</template>

<script setup>
import {Delete, Edit, InfoFilled} from '@element-plus/icons-vue'
import {defineStore} from 'pinia'
import {useDelete} from "@/utils/useDelete";
import http from "@/utils/request";
import {onMounted, ref, watch} from 'vue'
import {postData} from "@/uses/handleData.js";
import {usePageData} from "@/uses/usePageData.js";
import {ElMessage} from 'element-plus';
import ProductImport from '@/components/ProductImport.vue';
import BatchDelete from '@/components/BatchDelete.vue';
import ProductDetail from '@/components/ProductDetail.vue';
import {useRouter} from 'vue-router';

const searchStore = defineStore('orderStore', {

  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 10,
        sortField: "id",
        sortMethod: "desc",
        shop: '',
        name: '',
        productCatalog: '',
        productGroup: ''
      }
    }
  }
})

const {searchObject} = searchStore();

// 商品分类树相关
const catalogTree = ref(null);
const catalogTreeData = ref([]);
const catalogTreeProps = {
  children: 'children',
  label: 'name'
};
const treeFilterText = ref('');
const selectedCatalogId = ref(null);

// 监听过滤文本变化
watch(treeFilterText, (val) => {
  catalogTree.value?.filter(val);
});

// 节点过滤方法
const filterCatalogNode = (value, data) => {
  if (!value) return true;
  return data.name.toLowerCase().includes(value.toLowerCase());
};

// 获取分类树数据
const getCatalogTreeData = async () => {
  try {
    let param = {};
    param.sortMethod = "asc";
    param.sortField = "sortNum";
    param.size = 500;
    param.fetch = 1;
    param.depth = 1;

    let res = await http.post("/productCatalog/list", param);
    if (res.code === 200) {
      catalogTreeData.value = res.data || [];
      // 获取每个分类下的商品数量
      await getProductCountByCatalog();
    }
  } catch (error) {
    console.error('获取分类树数据失败:', error);
  }
};

// 获取每个分类下的商品数量
const getProductCountByCatalog = async () => {
  try {
    // 尝试调用商品分类计数接口
    let res = await http.post("/product/countByCategory", {});
    if (res.code === 200 && res.data) {
      // 更新分类树数据，添加商品数量
      updateCatalogTreeWithCount(catalogTreeData.value, res.data);
    }
  } catch (error) {
    console.error('获取分类商品数量失败:', error);
    console.log('尝试替代方法获取商品分类计数');
    // 如果接口不存在，则尝试一个替代方案：查询每个分类的商品
    try {
      await getProductCountByCatalogAlternate();
    } catch (altError) {
      console.error('替代方法也失败:', altError);
    }
  }
};

// 替代方法：为每个分类分别查询商品数量
const getProductCountByCatalogAlternate = async () => {
  const processCatalogNode = async (nodes) => {
    if (!nodes || nodes.length === 0) return;

    for (const node of nodes) {
      // 查询该分类下的商品数量
      try {
        const queryParams = {
          productCatalog: node.id,
          size: 1, // 只需要获取总数，不需要实际数据
          no: 1
        };
        const res = await http.post("/product/search", queryParams);
        if (res.code === 200) {
          node.count = res.total || 0;
        }
      } catch (err) {
        console.error(`获取分类 ${node.id} 的商品数量失败:`, err);
        node.count = 0;
      }

      // 递归处理子节点
      if (node.children && node.children.length > 0) {
        await processCatalogNode(node.children);
      }
    }
  };

  await processCatalogNode(catalogTreeData.value);
};

// 递归更新分类树节点的商品数量
const updateCatalogTreeWithCount = (nodes, countData) => {
  if (!nodes || nodes.length === 0) return;

  nodes.forEach(node => {
    // 在countData中查找对应的分类ID
    const countItem = countData.find(item => item.categoryId === node.id);
    if (countItem) {
      node.count = countItem.count;
    } else {
      node.count = 0;
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      updateCatalogTreeWithCount(node.children, countData);
    }
  });
};

// 处理节点点击
const handleCatalogNodeClick = (data) => {
  selectedCatalogId.value = data.id;
  searchObject.productCatalog = data.id;
  search();
};

// 清除分类筛选
const clearCatalogFilter = () => {
  selectedCatalogId.value = null;
  searchObject.productCatalog = '';
  // 清除树选中状态
  catalogTree.value?.setCurrentKey(null);
  search();
};

// 完全清除所有搜索条件
const clearAllSearch = () => {
  searchObject.shop = null;
  searchObject.state = null;
  searchObject.name = '';
  searchObject.productCatalog = '';
  selectedCatalogId.value = null;
  // 清除树选中状态
  catalogTree.value?.setCurrentKey(null);
  search();
};

// 刷新分类树
const refreshCatalogTree = () => {
  getCatalogTreeData();
};

// 初始化加载分类树
onMounted(async () => {
  await getCatalogTreeData();

  let param = {};
  param.model = "product_list";
  param.filters = searchObject;
    await http.post("/data/summary", param);

});

const {pageData, sizeChange, pageChange, search, changeTableSort, loading} = usePageData("product_list", searchObject);
const {dialogVisible, deleteData, handleDelete} = useDelete("/product/delete", search);
const router = useRouter();

// 商品详情抽屉相关
const detailDrawerVisible = ref(false);
const currentProductId = ref('');

// 显示商品详情抽屉
const showView = (row) => {
  currentProductId.value = row.id;
  detailDrawerVisible.value = true;
};

// 处理从详情抽屉点击编辑按钮的事件
const handleEditFromDetail = (productDetail) => {
  editView(productDetail);
};

// 添加商品
const addView = () => {
  router.push({
    path: '/product/add',
    query: {}
  });
};

// 编辑商品
const editView = (row) => {
  router.push({
    path: '/product/update',
    query: {
      id: row.id,
      name: row.name
    }
  });
};

const updateProductState=async (row) => {
  let param = {};
  param.id = row.id;
  param.state = row.state;
  await postData("product_update_state", param);
  await search();
}

// Excel导入相关
const importDialogVisible = ref(false);

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
};

// 处理导入成功事件
const handleImportSuccess = (result) => {
  if (result.success > 0) {
    ElMessage.success(`导入完成：成功${result.success}个，失败${result.failed}个`);
    // 刷新列表
    search();
  }
};

// 批量删除相关
const selectedRows = ref([]);
const batchDeleteDialogVisible = ref(false);

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 显示批量删除对话框
const showBatchDeleteDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  batchDeleteDialogVisible.value = true;
};

// 处理批量删除成功
const handleBatchDeleteSuccess = (result) => {
  if (result.success > 0) {
    // 刷新列表
    search();
    // 清空选中
    selectedRows.value = [];
  }
};
</script>

<style scoped>
.product-container {
  height: calc(100vh - 80px);
}
.data-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止容器出现滚动条 */
  border: none;
}


:deep(.el-table) {
  --el-table-border-color: #dcdfe6;
  flex: 1; /* 表格占满剩余空间 */
  overflow: auto; /* 内容过多时滚动 */
}
.catalog-aside {
  border-right: 1px solid #e6e6e6;
  padding: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.tree-container {
  flex: 1;
  overflow: auto;
  margin-right: -5px; /* 防止滚动条占用空间 */
  padding-right: 5px;
}

.filter-input {
  margin-bottom: 10px;
  flex-shrink: 0;
}

.product-main {
  padding: 10px;
  overflow: auto;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-shrink: 0;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 15px;
}

.tree-title {
  font-weight: bold;
  font-size: 16px;
  position: relative;
  padding-left: 8px;
}

.tree-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 16px;
  background-color: #409eff;
  border-radius: 1px;
}

.catalog-tree {
  height: 100%;
  overflow: visible;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.node-count {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 10px;
}

/* 树节点样式 */
:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
}

/* 美化树节点 */
:deep(.el-tree-node) {
  position: relative;
  padding-left: 16px;
}

:deep(.el-tree-node__children) {
  padding-left: 16px;
}

:deep(.el-tree-node.is-expanded > .el-tree-node__children) {
  position: relative;
}

:deep(.el-tree-node.is-expanded > .el-tree-node__children::before) {
  content: "";
  position: absolute;
  left: 5px;
  top: 0;
  height: 100%;
  border-left: 1px dashed #d9d9d9;
}

/* 添加悬停效果 */
:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

/* 修复滚动问题 */
:deep(.el-tree) {
  overflow: visible;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
</style>

